//
//  UILabel+Ex.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/20.
//

public extension UILabel {
    /// 快速创建 UILabel
    /// - Parameters:
    ///   - text: 文本内容
    ///   - font: 字体
    ///   - textColor: 文本颜色
    ///   - textAlignment: 文本对齐方式
    ///   - numberOfLines: 行数，默认 1
    ///   - backgroundColor: 背景颜色
    ///   - adjustsFontSizeToFitWidth: 是否自适应宽度，默认 false
    ///   - cornerRadius: 圆角，默认 0
    /// - Returns: 配置好的 UILabel 实例
    static public func createLabel(text: String? = nil,
                            font: UIFont? = nil,
                            textColor: UIColor? = nil,
                            textAlignment: NSTextAlignment = .left,
                            numberOfLines: Int = 0,
                            backgroundColor: UIColor? = nil,
                            adjustsFontSizeToFitWidth: Bool = false,
                            cornerRadius: CGFloat = 0) -> UILabel {
        let label = UILabel()
        label.setUpLabel(
            text: text,
            font: font,
            textColor: textColor,
            textAlignment: textAlignment,
            numberOfLines: numberOfLines,
            backgroundColor: backgroundColor,
            adjustsFontSizeToFitWidth: adjustsFontSizeToFitWidth,
            cornerRadius: cornerRadius
        )
        return label
    }
    
    
    public func setUpLabel(text: String? = nil,
                            font: UIFont? = nil,
                            textColor: UIColor? = nil,
                            textAlignment: NSTextAlignment = .left,
                            numberOfLines: Int = 0,
                            backgroundColor: UIColor? = nil,
                            adjustsFontSizeToFitWidth: Bool = false,
                            cornerRadius: CGFloat = 0) {
        let label = self
        
        // 设置文本内容
        label.text = text
        
        // 设置字体
        if let font = font {
            label.font = font
        }
        
        // 设置文本颜色
        if let textColor = textColor {
            label.textColor = textColor
        }
        
        // 设置文本对齐方式
        label.textAlignment = textAlignment
        
        //阿拉伯语适配
        if kIsRTL {
            label.semanticContentAttribute = .forceRightToLeft
            if textAlignment == .left {
                label.textAlignment = .right
            }else if textAlignment == .right {
                label.textAlignment = .left
            }
        }

        // 设置行数
        label.numberOfLines = numberOfLines
        
        // 设置背景颜色
        if let backgroundColor = backgroundColor {
            label.backgroundColor = backgroundColor
        }
        
        // 设置是否自适应宽度
        label.adjustsFontSizeToFitWidth = adjustsFontSizeToFitWidth
        
        // 设置圆角
        if cornerRadius > 0 {
            label.layer.cornerRadius = cornerRadius
            label.layer.masksToBounds = true
        }
    }
    
    
    
    
    /// 设置行间距
    /// - Parameters:
    ///   - lineSpacing: 行间距
    ///   - alignment: 对齐方式（默认为左对齐）
    func setLineSpacing(_ lineSpacing: CGFloat) {
        guard let text = self.text else { return }
        
        // 创建 NSMutableAttributedString
        let attributedString = NSMutableAttributedString(string: text)
        
        // 创建段落样式
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = lineSpacing
        paragraphStyle.alignment = self.textAlignment
        
        // 应用段落样式到整个文本
        attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedString.length))
        
        // 设置属性文本
        self.attributedText = attributedString
    }
}



public extension UILabel {
    var textHeight: CGFloat {
        if let textHeight = text?.height(ofFont: font, maxWidth: width > 0 ? width : .max) {
            return textHeight
        }
        return 0
    }
    var textWidth: CGFloat {
        if let textWidth = text?.width(ofFont: font, maxHeight: height > 0 ? height : .max) {
            return textWidth
        }
        return 0
    }
    var textSize: CGSize {
        if let textSize = text?.size(ofFont: font, maxWidth: .max, maxHeight: .max) {
            return textSize
        }
        return .zero
    }
}

public extension UILabel {
    //用 label 计算更加精准
     static func getAttributedTextSize(attributedText:NSAttributedString,maxWidth:CGFloat) -> CGSize{
        let label = UILabel()
        label.attributedText = attributedText
        label.numberOfLines = 0
        var size = label.sizeThatFits(CGSize(width: maxWidth, height: .greatestFiniteMagnitude))
        return size
    }
}

public extension UILabel {
    func applyGradient(colors: [UIColor], locations: [NSNumber]? = nil, startPoint: CGPoint = CGPoint(x: 0.0, y: 0.5), endPoint: CGPoint = CGPoint(x: 1.0, y: 0.5)) {
        
        if bounds.size == .zero { return }
        
        // 移除旧的渐变层（如果存在）
        removeExistingGradientLayer()
        self.alpha = 1
        self.isHidden = false
        // 创建渐变图层
        let gradientLayer = CAGradientLayer()
        gradientLayer.name = "GradientTextLayer"
        gradientLayer.frame = self.bounds
        gradientLayer.colors = colors.map { $0.cgColor }
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endPoint

        // 创建图层遮罩
        let textImage = imageFromText()
        let maskLayer = CALayer()
        maskLayer.contents = textImage?.cgImage
        maskLayer.frame = self.bounds
        gradientLayer.mask = maskLayer

        self.layer.addSublayer(gradientLayer)
    }
    
    /// 移除已有的渐变图层
    private func removeExistingGradientLayer() {
        self.layer.sublayers?.removeAll(where: { $0.name == "GradientTextLayer" })
    }

    /// 将 Label 渲染成图像
    private func imageFromText() -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0)
        defer { UIGraphicsEndImageContext() }
        if let context = UIGraphicsGetCurrentContext() {
            self.layer.render(in: context)
            return UIGraphicsGetImageFromCurrentImageContext()
        }
        return nil
    }
    
}
